package app;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.cyan.tools.util.RxBus;
import com.example.menhoo.toollibrary.common.assist.IMEHelper;
import com.example.menhoo.toollibrary.common.utils.HandlerUtil;
import com.example.menhoo.toollibrary.common.utils.InputMethodUtils;
import com.lidroid.xutils.util.LogUtils;
import com.socks.library.KLog;
import com.zejian.emotionkeyboard.utils.SharedPreferencedUtils;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;

import application.AppApplication;
import application.HttpUrlConstant;
import custom.PinnedSectionListView;
import custom.kyletterfilter.KyLetterfilter;
import custom.kyletterfilter.OnLetterfilterListener;
import fragment.contact.ContactsAdapter;
import fragment.contact.ContactsModel;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import mainUI.AppActivity;
import menhoo.com.i8officelibrary.R;
import model.EmployeeItemDBModel;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import tools.ToastUtil;
import utils.Utils;
import view.ThreePointLoadingView;

/**
 * Created by zhukang on 2018/6/21.
 */

public class ContactsSearch extends AppActivity implements View.OnClickListener, TextWatcher, TextView.OnEditorActionListener {

    private static final String TAG = "ContactsSearch";

    private PinnedSectionListView listView;
    private Button searchBtn;
    private EditText searchEt;
    private List<EmployeeItemDBModel> list;
    private List<EmployeeItemDBModel> allList;
    private List<EmployeeItemDBModel> searchList;
    private ContactsAdapter adapter;
    private ContactsModel model;
    private KyLetterfilter kyLetterfilter;
    private ThreePointLoadingView loading;
    private Call call;
    private Observable<String> observable;
    private Disposable disposable;
    private boolean isSearch = false;
    private Disposable filterDisposable;

    @Override
    public void onClick(View view) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitleDisplay(false);
        setContentView(R.layout.contact_search);
        setTitle("人员搜索");
        initView();
        initRxJava();
        requestAllEmpl();
    }

    private void initRxJava() {
        observable = RxBus.get().register("refreshContact", String.class);
        disposable = observable.subscribe(new Consumer<String>() {
            @Override
            public void accept(final String result) {
                Executors.newCachedThreadPool().execute(new Runnable() {
                    @Override
                    public void run() {
//                        final String resultCache = SharedPreferencedUtils.getString(ContactsSearch.this, "contacts");
//                        if (TextUtils.isEmpty(resultCache) || !resultCache.equals(result)) {
//                            SharedPreferencedUtils.setString(ContactsSearch.this, "contacts", result);
//                        }
                        parseResult(result);
                    }
                });
            }
        });
    }

    private void initView() {
        findViewById(R.id.btn_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
                IMEHelper.hideIME(ContactsSearch.this, true);
            }
        });
        searchEt = (EditText) findViewById(R.id.searchEt);
        searchEt.setOnEditorActionListener(this);
        searchEt.addTextChangedListener(this);
        loading = (ThreePointLoadingView) findViewById(R.id.loading);
        searchBtn = (Button) findViewById(R.id.searchBtn);
        searchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isSearch = true;
                IMEHelper.hideIME(ContactsSearch.this, true);
                final String edit = searchEt.getText().toString();
                //如果输入框无值，获取所有用户
                if (TextUtils.isEmpty(edit)) {
                    list.clear();
                    list.addAll(allList);
                    adapter.notifyDataSetChanged();
                    isSearch = false;
                } else {//如果有值，进行筛选
                    if (Utils.isInteger(edit)) {
                        loading.play();
                        Executors.newCachedThreadPool().execute(new Runnable() {
                            @Override
                            public void run() {
                                searchListByNumber(edit);
                            }
                        });
                    } else {
                        filterList(allList, edit);

                    }
                }
            }
        });
        listView = (PinnedSectionListView) findViewById(R.id.PinnedSectionList);
        list = new ArrayList<EmployeeItemDBModel>();
        adapter = new ContactsAdapter(this, list, false);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                EmployeeItemDBModel item = (EmployeeItemDBModel) parent.getAdapter().getItem(position);
                if (TextUtils.isEmpty(item.EmplID) && TextUtils.isEmpty(item.DeptID)) {
                    LogUtils.e("no EmplID and no DeptID");
                } else {
                    //判断点击的是标题头还是真正的选项
                    if (item.type == EmployeeItemDBModel.ITEM && !TextUtils.isEmpty(item.EmplID)) {
                        Intent it = new Intent(ContactsSearch.this, ContactInfo.class);
                        it.putExtra("emplID", item.EmplID);
                        startActivity(it);
                    }
                }
            }
        });
        model = new ContactsModel();

        kyLetterfilter = (KyLetterfilter) findViewById(R.id.kyLetterfilter1);
        kyLetterfilter.setOnLetterfilterListener(new OnLetterfilterListener() {
            @Override
            public void start() {
            }

            @Override
            public void end() {
            }

            @Override
            public void letterChanged(String letter) {
                if (letter.equals("#")) {
                    listView.setSelection(0);
                    return;
                }
                if (adapter == null) {
                    return;
                }
                int index = -1;//下标
                for (int i = 0; i < adapter.getAllData().size(); i++) {
                    EmployeeItemDBModel employeeItemDBModel = adapter.getAllData().get(i);
                    String firstChar = employeeItemDBModel.Name.substring(0, 1);
                    firstChar = firstChar.toUpperCase();
                    if (firstChar.equals(letter)) {
                        index = i;
                        break;
                    }
                }
                if (index != -1)
                    listView.setSelection(index);
            }
        });
    }

    private void searchListByNumber(String edit) {
        String urlF = HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant.SEARCH_PEOPLE_BY_NUMBER) + "?__session__=" + AppApplication.getSession() + "&contact=" + edit;
        KLog.e("urlF:" + urlF);
        OkHttpClient client = new OkHttpClient();
        Call call = client.newCall(new Request.Builder()
                .url(urlF)
                .get()
                .build());
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                isSearch = false;
                HandlerUtil.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        loading.stop();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                KLog.e("search result" + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (jsonObject.getBoolean("Succeed")) {
                        searchList = model.getEmployeeItemDBModelsFromSearch(jsonObject);
                        list.clear();
                        list.addAll(searchList);
                        HandlerUtil.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (isFinishing() || isDestroyed()) {
                                    return;
                                }
                                adapter.notifyDataSetChanged();
                            }
                        });
                    } else {
                        final String message = jsonObject.optString("Message");
                        if (!TextUtils.isEmpty(message)) {
                            HandlerUtil.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    ToastUtil.show(ContactsSearch.this, message);
                                }
                            });
                        }
                    }
                } catch (Exception e) {
                    KLog.e(e.getMessage());
                }
                HandlerUtil.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        loading.stop();
                    }
                });
                isSearch = false;
            }
        });
    }

    /**
     * 根据搜索进行查询
     *
     * @param allList
     * @param searchString
     * @return
     */
    private void filterList(final List<EmployeeItemDBModel> allList, final String searchString) {
        if (filterDisposable != null) {
            filterDisposable.dispose();
        }
        if(allList==null){
            return;
        }
        filterDisposable = Observable.just(allList)
                .map(new Function<List<EmployeeItemDBModel>, List<EmployeeItemDBModel>>() {
                    @Override
                    public List<EmployeeItemDBModel> apply(List<EmployeeItemDBModel> employeeItemDBModels) throws Exception {
                        List<EmployeeItemDBModel> aList = new ArrayList<>();
                        aList.add(new EmployeeItemDBModel(EmployeeItemDBModel.SECTION, "#"));
                        for (EmployeeItemDBModel model : allList) {
                            if (model.type == EmployeeItemDBModel.SECTION) {
                                continue;
                            }
                            if (model.Name.indexOf(searchString) != -1) {
                                aList.add(model);
                            }
                        }
                        return aList;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(new DisposableObserver<List<EmployeeItemDBModel>>() {
                    @Override
                    public void onNext(List<EmployeeItemDBModel> employeeItemDBModels) {
                        searchList = employeeItemDBModels;
                        list.clear();
                        list.addAll(searchList);
                        adapter.notifyDataSetChanged();
                        isSearch = false;
                    }

                    @Override
                    public void onError(Throwable e) {

                    }


                    @Override
                    public void onComplete() {
                    }
                });
//        List<EmployeeItemDBModel> aList = new ArrayList<>();
//        aList.add(new EmployeeItemDBModel(EmployeeItemDBModel.SECTION, "#"));
//        for (EmployeeItemDBModel model : allList) {
//            if (model.type == EmployeeItemDBModel.SECTION) {
//                continue;
//            }
//            String name = Utils.removeAllBlank(model.Name).replace(" ","");
////            if(name.indexOf("晨")!=-1){
//                KLog.e(name);
////            }
//            if (name.indexOf(searchString)!=-1) {
//                aList.add(model);
//            }
//        }
//        return aList;
    }

    public void requestAllEmpl() {
        loading.play();
        Executors.newCachedThreadPool().submit(new Runnable() {
            @Override
            public void run() {
                final String resultCache = SharedPreferencedUtils.getString(ContactsSearch.this, "contacts");
                    parseResult(resultCache);

            }
        });
    }

    public void parseResult(final String result) {
        if (TextUtils.isEmpty(result)) {
            return;
        }
        try {
            JSONObject jsonObject = new JSONObject(result);
            if (jsonObject.getBoolean("Succeed")) {
                allList = model.getEmployeeItemDBModelsFromAll(jsonObject);
                if (isSearch || (searchList != null && searchList.size() > 0)) {
                    return;
                }
                list.clear();
                list.addAll(allList);
                HandlerUtil.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (isFinishing() || isDestroyed()) {
                            return;
                        }
                        adapter.notifyDataSetChanged();
                    }
                });
            }
        } catch (Exception e) {
            LogUtils.e(e.getMessage() + "");
        }
        HandlerUtil.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                loading.stop();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (call != null && !call.isCanceled()) {
            call.cancel();
        }
        if (disposable != null && !disposable.isDisposed()) disposable.dispose();
        if (observable != null) RxBus.get().unregister("refreshContact", observable);
        if (filterDisposable != null) filterDisposable.dispose();
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        String edit = String.valueOf(charSequence);
        //如果输入框无值，获取所有用户
        if (TextUtils.isEmpty(edit)) {
            list.clear();
            list.addAll(allList);
            adapter.notifyDataSetChanged();
        }
        //如果有值，进行筛选
        else {
            if (Utils.isInteger(edit)) {
                return;
            }
            filterList(allList, edit);
        }
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }

    @Override
    public boolean onEditorAction(TextView textView, int keyCode, KeyEvent keyEvent) {
        if (keyCode == EditorInfo.IME_ACTION_SEARCH) {
            searchBtn.performClick();
        }
        return false;
    }
}
